package com.taotao.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.taoato.sso.service.UserLoginService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.credentialsmatcher.CustomCredentialsMatcher;
import com.taotao.pojo.TbUser;

public class ManagerRealm extends AuthorizingRealm{

	private UserLoginService userService;
	
	public void setUserService(UserLoginService userService) {
		this.userService = userService;
	}
	/*private CacheManager cacheManager;
	
	
	public CacheManager getCacheManager() {
		return cacheManager;
	}
 
	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}
 
	*//**
	 * 初始化密码部分验证条件
	 *//*
	
    public void initCredentialsMatcher() {
		//该句作用是重写shiro的密码验证，让shiro用自定义的验证  
    	CustomCredentialsMatcher customCredentialsMatcher = new CustomCredentialsMatcher(cacheManager);
        setCredentialsMatcher(customCredentialsMatcher);  
    }*/
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		System.out.println("执行了授权。。。。");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermission("商品管理");
		//获得已登录认证的用户
		TbUser user = (TbUser)principal.getPrimaryPrincipal();
		return info;
	}
	/**
	 * 认证
	 * 返回null认证失败
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行了认证。。。。");
		//1.将UsernamePasswordToken转成事先类获得从页面传过来的用户名和密码
		UsernamePasswordToken upt = (UsernamePasswordToken)token;
		//将字符数组转成字符串
		String password = new String(upt.getPassword());
		//验证是否登录成功
		TaotaoResult result = userService.userLogin(upt.getUsername(), password);
		//如果验证成功
		if(result.getStatus() == 200) {
			TaotaoResult result2 = userService.getToken(result.getData().toString());
			TbUser user = (TbUser)result2.getData();
			/*TbUser user = new TbUser();
			user.setUsername(upt.getUsername());*/
			//返回认证信息
			//参数1：主角，就是登录的用户
			//参数2：证书或凭证，密码
			//参数3：当前realm的名称
			return new SimpleAuthenticationInfo(user, password, getName());
		}
		return null;
	}

}
